package hr.web.jsf.validators;

import hr.web.jsf.FacesMessageUtil;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.commons.validator.EmailValidator;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

@BypassInterceptors
@Name(value = "emailValidator")
@org.jboss.seam.annotations.faces.Validator
public class EmailAddressValidator implements Validator {

	@Override
	public void validate(final FacesContext facesContext,
			final UIComponent uiComponent, final Object object)
			throws ValidatorException {

		if (object != null) {

			// If the specified object is a string and is invalid, then add
			// an error message to the faces context and throw an exception.
			if (object instanceof String) {
				final String emailAddress = (String) object;

				if (emailAddress.length() > 0) {

					if (!EmailValidator.getInstance().isValid(emailAddress)) {
						final String key = EmailAddressValidator.class
								.getName()
								+ ".invalidEmailAddress";

						throw new ValidatorException(FacesMessageUtil
								.getFacesMessage("Language", facesContext,
										FacesMessage.SEVERITY_ERROR, key));
					}
				}
			}

			// Otherwise, if the specified object is not a string, then add
			// an error message to the faces context and throw an exception.
			else {
				final String key = EmailAddressValidator.class.getName()
						+ ".invalidType";
				throw new ValidatorException(FacesMessageUtil.getFacesMessage(
						"Language", facesContext, FacesMessage.SEVERITY_ERROR,
						key, new String[] { object.getClass().getName() }));
			}

			// Otherwise, do not throw an exception and finish normally (which
			// means validation passed).
		}
	}

}
